package com.ruoyi.walmart.service.shipments.impl;
import java.util.stream.Collectors;
import java.util.function.Function;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.WalmartConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.walmart.domain.auth.ShopAuth;
import com.ruoyi.walmart.domain.shipments.*;
import com.ruoyi.walmart.dto.ShipmentItemDTO;
import com.ruoyi.walmart.http.WalmartRequest;
import com.ruoyi.walmart.mapper.shipments.ShipmentItemMapper;
import com.ruoyi.walmart.mapper.shipments.ShipmentMapper;
import com.ruoyi.walmart.mapper.shipments.ShipmentStockMapper;
import com.ruoyi.walmart.service.auth.ShopAuthService;
import com.ruoyi.walmart.service.shipments.ShipmentItemService;
import com.ruoyi.walmart.service.shipments.ShipmentService;
import com.ruoyi.walmart.service.shipments.ShipmentStockService;
import com.ruoyi.walmart.util.walmartUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class ShipmentItemServiceImpl implements ShipmentItemService {

    @Autowired
    private ShipmentItemMapper shipmentItemMapper;
    @Autowired
    private ShipmentMapper shipmentMapper;
    @Autowired
    private ShipmentService shipmentService;
    @Autowired
    private ShipmentStockMapper shipmentStockMapper;
    @Autowired
    private ShopAuthService shopAuthService;
    @Autowired
    private ShipmentStockService shipmentStockService;
    @Override
    public List<ShipmentItem> selectAllList(ShipmentItem shipmentItem) {
        return shipmentItemMapper.selectAllList(shipmentItem);
    }

    @Override
    public int shipmentItemInsertList(List<ShipmentItem> shipmentItemList) {
        return shipmentItemMapper.shipmentItemInsertList(shipmentItemList);
    }

    @Override
    public int deleteShipmentItemByAuthId(Long authId) {
        return shipmentItemMapper.deleteShipmentItemByAuthId(authId);
    }

    /**
     * shipmentId获取发货信息
     * @return
     */
    @Override
    @Transactional
    public int getShipmentItemByShipmentId(String shipmentId, ShopAuth shopAuth, InboundShipment inboundShipment) {

        ShipmentCondition shipmentCondition = new ShipmentCondition();
        shipmentCondition.setOffset(0);
        shipmentCondition.setLimit(300);
        shipmentCondition.setShipmentId(shipmentId);

        JSONObject jsonObject = walmartUtil.listShipmentUs(shipmentCondition,shopAuth);
        ShipmentPayload shipmentPayload = JSON.parseObject(jsonObject.toString(), ShipmentPayload.class);
        if(jsonObject == null){
            return 0 ;
        }
        Map<String, Object> paramMap = null;
        ShipmentItem shipmentItem = null;
        Shipment shipment =  null;
        List<ShipmentItem> shipmentItemList = new ArrayList<>();
        List<Shipment> shipmentList = new ArrayList<>();
        int rows = 0;
        if(shipmentPayload.getHeaders().getTotalCount() != 0) {
            List<ShipmentPayload.Shipment> payload = shipmentPayload.getPayload();
            for (ShipmentPayload.Shipment newShipment:payload) {
                shipment = new Shipment();
                String uuid = IdUtils.fastSimpleUUID();
                BeanUtils.copyProperties(newShipment,shipment);
                shipment.setShiptId(uuid);
                shipment.setAuthId(shopAuth.getAuthId());
                shipment.setShipFcName(newShipment.getShipToAddress().getFcName());
                shipment.setShipAddressLine(newShipment.getShipToAddress().getAddressLine1());
                shipment.setShipCity(newShipment.getShipToAddress().getCity());
                shipment.setShipStateCode(newShipment.getShipToAddress().getStateCode());
                shipment.setShipCountryCode(newShipment.getShipToAddress().getCountryCode());
                shipment.setShipPostalCode(newShipment.getShipToAddress().getPostalCode());
                shipment.setReturnAddressLine(newShipment.getReturnAddress().getAddressLine1());
                shipment.setReturnCity(newShipment.getReturnAddress().getCity());
                shipment.setReturnStateCode(newShipment.getReturnAddress().getStateCode());
                shipment.setReturnCountryCode(newShipment.getReturnAddress().getCountryCode());
                shipment.setReturnPostalCode(newShipment.getReturnAddress().getPostalCode());
                List<String> trackingNo = newShipment.getTrackingNo();
                String json = StringUtils.join(trackingNo,",");
                shipment.setTrackingNo(json);
                paramMap = new HashMap<>();
                paramMap.put("shipmentId",shipment.getShipmentId());
                paramMap.put("limit","300");
                paramMap.put("offset","0");
                String url = WalmartConstant.BASE_URL+WalmartConstant.GET_SHIPMENTS_ITEM_US_URL;
                String request = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);
                ShipmentItemPayload shipmentItemPayload = JSON.parseObject(request, ShipmentItemPayload.class);
                List<ShipmentItemPayload.Payload> payloadList = shipmentItemPayload.getPayload();
                for (ShipmentItemPayload.Payload itemPayload:payloadList) {
                    shipmentItem = new ShipmentItem();
                    BeanUtils.copyProperties(itemPayload,shipmentItem);
                    String _uuid = IdUtils.fastSimpleUUID();
                    shipmentItem.setShipItemId(_uuid);
                    shipmentItemList.add(shipmentItem);
                    
                }
                shipmentList.add(shipment);
            }
            //删除货运明细
            shipmentItemMapper.deleteItemsByShipmentId(shipmentId);
            //删除货运主表
            shipmentMapper.deleteByShipmentId(shipmentId);

            rows = shipmentItemMapper.shipmentItemInsertList(shipmentItemList);
            shipmentMapper.shipmentInsertList(shipmentList);
        }

        return rows;
    }

    @Override
    @Transactional
    public int updatedShipmentQty(ShipmentItem shipmentItem) {
        //更新货运数量
        shipmentItemMapper.updatedShipmentQty(shipmentItem);
        //更新主表数量
        return shipmentMapper.updatedShipmentUnits(shipmentItem);
    }
    /**
     * 货件明细
     * @param shipmentItem
     * @return
     */
    @Override
    public List<ShipmentItemDTO> getShipmentItemDTO(ShipmentItemDTO shipmentItem) {
        return shipmentItemMapper.getShipmentItemDTO(shipmentItem);
    }
    /**
     * 修改货件明细发货数0
     * @param shipmentId
     * @return
     */
    @Override
    public int updateShipmentItemQty(String shipmentId) {
        return shipmentItemMapper.updateShipmentItemQty(shipmentId);
    }
    /**
     * 根据shipmentId列表删除ShipmentItems
     * @param shipmentIds
     * @return
     */
    @Override
    public void deleteShipmentItemsByShipmentIds(List<String> shipmentIds) {
        if (shipmentIds != null && !shipmentIds.isEmpty()) {
            shipmentItemMapper.deleteShipmentItemsByShipmentIds(shipmentIds);
        }
    }
    /**
     * shipmentId获取发货信息
     * @return
     */
    @Override
    @Transactional
    public int updateShipmentStockReceivedQty(Long authId) {
        List<ShipmentStock> shipmentStockList = shipmentStockMapper.selectList(new LambdaQueryWrapper<ShipmentStock>()
                .isNull(ShipmentStock::getActualDeliveryDate)
                .isNotNull(ShipmentStock::getStockId)
                .eq(ShipmentStock::getStatus,0L)
                .eq(ShipmentStock::getAuthId,authId)
                .select(ShipmentStock::getShipmentId, ShipmentStock::getAuthId)
                .groupBy(ShipmentStock::getShipmentId, ShipmentStock::getAuthId));

        AtomicInteger rows = new AtomicInteger(0);
        shipmentStockList.forEach(ss -> {
            String shipmentId = ss.getShipmentId();
            ShopAuth shopAuth = shopAuthService.selectByAuthId(authId);

            ShipmentCondition shipmentCondition = new ShipmentCondition();
            shipmentCondition.setOffset(0);
            shipmentCondition.setLimit(300);
            shipmentCondition.setShipmentId(shipmentId);


            JSONObject jsonObject = walmartUtil.listShipmentUs(shipmentCondition,shopAuth);
            ShipmentPayload shipmentPayload = JSON.parseObject(jsonObject.toString(), ShipmentPayload.class);
            if (jsonObject == null || shipmentPayload.getHeaders().getTotalCount() == 0) {
               return;
            }
            if(shipmentPayload.getHeaders().getTotalCount() != 0) {
                List<ShipmentPayload.Shipment> payload = shipmentPayload.getPayload();
                for (ShipmentPayload.Shipment newShipment:payload) {
                    LocalDateTime actualDeliveryDate = newShipment.getActualDeliveryDate();
                    LambdaUpdateWrapper<ShipmentStock> wrapper = new LambdaUpdateWrapper<ShipmentStock>()
                            .eq(ShipmentStock::getShipmentId, shipmentId)
                            .eq(ShipmentStock::getAuthId, authId)
                            .eq(ShipmentStock::getStatus,0L)
                            .set(ShipmentStock::getActualDeliveryDate, actualDeliveryDate);
                    shipmentStockService.update(wrapper);
                }
            }
        });
        return rows.get();
    }
}
